import { memo, useState, useEffect } from "react"
import { TreeSelect } from "antd"

import { postJson } from '@/utils/http/linitly.request.js'

const DictItemTreeSelect = ({
  value,
  onChange,
  // 字典id
  dictId
}) => {

  const [ items, setItems ] = useState([])

  useEffect(() => {
    dictId && getItems()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dictId])

  return (
    <TreeSelect treeDefaultExpandAll={true} value={value} placeholder="请选择" treeLine={true} treeData={items} onSelect={onSelect} />
  )

  function getItems() {
    postJson(`/sysDataDictItem/findByDictId/${dictId}`)
    .then((res) => {
      setItems(getTreeSelectData(res))
    })
  }

  function getTreeSelectData(datas) {
    return datas.map(value => ({
        title: value.text,
        value: value.value
      })
    )
  }

  function onSelect(value) {
    onChange(value)
  }
}


export default memo(DictItemTreeSelect)
